package com.net.library.nettoken;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.net.library.bean.AuthResult;
import com.net.library.bean.IRequstCode;
import com.net.library.bean.TokenError;
import com.net.library.constant.AuthParamsValue;
import com.net.library.constant.SharePreKey;
import com.net.library.interfaces.RequestListener;
import com.net.library.interfaces.ServerDataInterface;
import com.net.library.util.NetErrStringUtils;
import com.net.library.util.SharedPreferencesUntil;
import com.socks.library.KLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;

/**
 * 作者： 吴昶 .
 * 时间: 2018/11/12 10:52
 * 功能简介：
 */
public class RetrofitConnection {

    @SuppressLint("StaticFieldLeak")
    private static RetrofitConnection retrofitConnection;

    /**
     * 单例 初始化
     * @return
     */
    public static RetrofitConnection getInstance(){
        if(retrofitConnection==null){
            retrofitConnection=new RetrofitConnection();
        }
        return retrofitConnection;
    }

    public <T extends IRequstCode> void enqueue(final Context context, final Call<T> requestCall, final int requestCode, final RequestListener<T> requestListener){
            getEnqueue(context,requestCall,requestCode,requestListener);
    }

    /**
     * 获取 token
     */
    public void getToken(final RequestListener requestListener){
        Call<AuthResult> callAuthResult = RetrofitTokenServer.getInstance()
                .createCallToken(ServerDataInterface.class)
                .getAuthToken(AuthParamsValue.GRANT_TYPE,
                        AuthParamsValue.SCOPE,
                        AuthParamsValue.CLIENT_ID,
                        AuthParamsValue.CLIENT_SECRET);
        RetrofitTokenServer.getInstance().enqueue(callAuthResult, 0, new RequestListener<AuthResult>() {
            @Override
            public void onResquestSuccess(AuthResult result) {
                try {
                    if (!TextUtils.isEmpty(result.getAccess_token())) {
                        SharedPreferencesUntil.saveValue(SharePreKey.ACCESS_TOKEN, result.getAccess_token());
                        if (requestListener != null) {
                            requestListener.onReResquest();
                        }
                    } else {
                        if (requestListener != null)
                            requestListener.onResquestError(0, -1, "服务器繁忙");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (requestListener != null)
                        requestListener.onResquestError(0, -1, "服务器繁忙");
                }
            }

            @Override
            public void onResquestError(int requestCode, int errorCode, String message) {
                if(requestListener!=null)
                    requestListener.onResquestError(requestCode,-1,"服务器繁忙");
            }

            @Override
            public void onReResquest() {

            }
        });
    }

    /**
     * 获取数据
     */
    private <T extends IRequstCode> void getEnqueue(final Context context, final Call<T> requestCall, final int requestCode, final RequestListener<T> requestListener){
        requestCall.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if(response.isSuccessful()) {
                    T result = response.body();
                    if (result == null) {
                        requestListener.onResquestError(requestCode,response.code(),
                                NetErrStringUtils.getErrString(context,response.code()));
                    }else {
                        requestListener.onResquestSuccess(result);
                    }
                }else {
                    try {
                        String json=response.errorBody().string();
                        KLog.d(json);
                        if(json.startsWith("<html>")){
                            requestListener.onResquestError(requestCode,response.code(),
                                    NetErrStringUtils.getErrString(context,response.code()));
                        }else {
                            Gson gson=new Gson();
                            TokenError code=gson.fromJson(json,TokenError.class);
                            if(code!=null && !TextUtils.isEmpty(code.getError()) && code.getError().equals("invalid_token")){
                                KLog.d(code.toString());
                                RetrofitTokenServer.getInstance().initToken();
                                getToken(requestListener);
                            }else {
                                requestListener.onResquestError(requestCode,response.code(),
                                        NetErrStringUtils.getErrString(context,response.code()));
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        requestListener.onResquestError(requestCode,response.code(),
                                NetErrStringUtils.getErrString(context,response.code()));
                    }
                }

            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                requestListener.onResquestError(requestCode,0,NetErrStringUtils.getErrString(context,t));
            }


        });
    }

}
